/**
 * 
 */
package com.hawkfly.interceptor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wbcs.config.component.application.report.ReportBean;
import com.wbcs.system.ReportRequest;
import com.wbcs.system.intercept.AbsPageInterceptor;

/**
 * 用于进行操作日志记录的通用页面拦截器类
 * @author hawkfly
 */
public class ItprOperateLog extends AbsPageInterceptor
{
    private static Log log = LogFactory.getLog(ItprOperateLog.class);
    @Override
	public void doStart(ReportRequest rrequest)
    {
        System.out.println("InterceptorOperateLog 加载页面"+rrequest.getPagebean().getId());
        log.info("加载页面"+rrequest.getPagebean().getId());
        Map map = rrequest.getPagebean().getMChildren();
    }

    @Override
	public void doStartSave(ReportRequest rrequest,List<ReportBean> lstSaveReportBeans)
    {
        /*if(usercode == null)
        rrequest.getWResponse().getMessageCollector().error("会话失效，请重新登录！",true);*/
       //判断会话是否失效
        Object usercode = rrequest.getRequest().getSession().getAttribute("usercode");
        Map<String, String> map = rrequest.getAttributes();
        Iterator<String> it = map.keySet().iterator();
        String selectKey = null;
        StringBuffer oprtype = new StringBuffer();
        String pageid = rrequest.getPagebean().getId();
        String accessMode = null;
        
        oprtype.append("pageid:");
        oprtype.append(pageid);
        oprtype.append(",event:");
        while(it.hasNext()){
            String key = it.next();
            if(key.endsWith("ACCESSMODE"))
                selectKey = key;
        }
        if(selectKey == null){//判断操作执行动作类型
            accessMode = docheckGeneralOperation(rrequest, lstSaveReportBeans);
        }else{
            accessMode = map.get(selectKey);
            if("update".equals(accessMode)){
                for(ReportBean rbean: lstSaveReportBeans){
                    List<Map<String,String>> lstInsertData = rrequest.getLstInsertedData(rbean);
                    List<Map<String,String>> lstUpdateData = rrequest.getLstUpdatedData(rbean);
                    List<Map<String,String>> lstDeleteData = rrequest.getLstDeletedData(rbean);
                    if(lstInsertData == null && lstUpdateData == null && lstDeleteData != null && lstDeleteData.size()>0)
                        accessMode = "delete";
                }
            }else if("add".equals(accessMode)){
                
            }else if("read".equals(accessMode) || "readonly".equals(accessMode)){
                accessMode = docheckGeneralOperation(rrequest, lstSaveReportBeans);
            }else{
                return;
            }
        }
        oprtype.append(accessMode);
        //执行日志插入动作
        Connection conn = rrequest.getConnection();
        String sql = "insert into CBSS_SYS_LOG(ID, MEM_CODE, OPR_TYPE, OPR_DATE, REMOTE_IP, REMARK) values(SEQ_ORGS.NEXTVAL, ?, ?, ?, ?, ?)";
        PreparedStatement ps = null;
        try
        {
           ps = conn.prepareStatement(sql);
           ps.setString(1,String.valueOf(usercode));
           ps.setString(2,oprtype.toString());
           ps.setTimestamp(3,new Timestamp(new java.util.Date().getTime()));
           ps.setString(4,getIpAddr(rrequest.getRequest()));
           ps.setString(5,rrequest.getRequest().getSession().getId());
           ps.executeUpdate();
        }catch(SQLException e)
        {
            // TODO Auto-generated catch block
            log.error("执行日志插入动作出错！", e);
            rrequest.getWResponse().getMessageCollector().error("日志插入错误","日志错误",e);
        }finally{
            try
            {
                ps.close();
            }catch(SQLException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
	public void doEndSave(ReportRequest rrequest,List<ReportBean> lstSaveReportBeans)
    {
        
    }

    @Override
	public void doEnd(ReportRequest rrequest)
    {
        System.out.println("InterceptorOperateLog 结束页面"+rrequest.getPagebean().getId());
        log.info("结束页面"+rrequest.getPagebean().getId());
    }
    
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    
   private String docheckGeneralOperation(ReportRequest rrequest,List<ReportBean> lstSaveReportBeans){
       String accessMode = null;
       for(ReportBean rbean: lstSaveReportBeans){
           List<Map<String,String>> lstInsertData = rrequest.getLstInsertedData(rbean);
           List<Map<String,String>> lstUpdateData = rrequest.getLstUpdatedData(rbean);
           List<Map<String,String>> lstDeleteData = rrequest.getLstDeletedData(rbean);
           if(lstInsertData!=null&&lstInsertData.size()>0){
               accessMode = "add-";
           }
           if(lstUpdateData!=null&&lstUpdateData.size()>0){
               accessMode = "update-";
           }
           if(lstDeleteData!=null&&lstDeleteData.size()>0){
               accessMode = "delete-";
           }
       }
       return accessMode;
   }
}

